// utils/auth.js

// 获取应用实例，增加安全检查
const getAppInstance = () => {
  try {
    return getApp()
  } catch (e) {
    console.error('获取应用实例失败:', e)
    return null
  }
}

// 用户身份验证
const authenticateUser = (userInfo) => {
  return new Promise((resolve, reject) => {
    const db = wx.cloud.database()
    
    // 获取用户openid
    wx.cloud.callFunction({
      name: 'login',
      data: {}
    }).then(res => {
      const openid = res.result.openid
      
      // 检查用户是否已存在
      return db.collection('users')
        .where({
          _openid: openid
        })
        .get()
    }).then(res => {
      if (res.data.length > 0) {
        // 用户已存在，直接验证通过
        resolve(res.data[0])
      } else {
        // 用户不存在，显示口令输入弹窗
        showPasscodeModal(userInfo, resolve, reject)
      }
    }).catch(err => {
      console.error('用户验证失败:', err)
      reject(err)
    })
  })
}

// 显示口令输入弹窗
const showPasscodeModal = (userInfo, resolve, reject) => {
  wx.showModal({
    title: '请输入身份验证口令',
    editable: true,
    placeholderText: '请输入您的身份验证口令',
    success: (res) => {
      if (res.confirm) {
        const passcode = res.content
        validatePasscode(passcode, userInfo, resolve, reject)
      } else {
        reject(new Error('用户取消验证'))
      }
    },
    fail: () => {
      reject(new Error('验证失败'))
    }
  })
}

// 验证口令
const validatePasscode = (passcode, userInfo, resolve, reject) => {
  const db = wx.cloud.database()
  
  // 根据口令判断用户身份
  let userRole = 'user'
  if (passcode === '13303076385') {
    userRole = 'admin'
  } else if (passcode === '15075718656') {
    userRole = 'user'
  } else {
    wx.showModal({
      title: '验证失败',
      content: '口令错误，无法使用小程序功能',
      showCancel: false,
      success: () => {
        reject(new Error('口令错误'))
      }
    })
    return
  }
  
  // 获取用户openid并保存用户信息
  wx.cloud.callFunction({
    name: 'login',
    data: {}
  }).then(res => {
    const openid = res.result.openid
    
    // 保存用户信息到数据库
    return db.collection('users').add({
      data: {
        _openid: openid,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        role: userRole,
        passcode: passcode,
        createTime: db.serverDate(),
        lastLoginTime: db.serverDate()
      }
    }).then(addRes => {
      // 返回用户信息
      resolve({
        _id: addRes._id,
        _openid: openid,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        role: userRole,
        passcode: passcode
      })
    })
  }).catch(err => {
    console.error('保存用户信息失败:', err)
    reject(err)
  })
}

// 检查用户是否已认证
const checkAuthentication = () => {
  return new Promise((resolve, reject) => {
    const db = wx.cloud.database()
    
    // 获取用户openid
    wx.cloud.callFunction({
      name: 'login',
      data: {}
    }).then(res => {
      const openid = res.result.openid
      
      // 检查用户是否已存在
      return db.collection('users')
        .where({
          _openid: openid
        })
        .get()
    }).then(res => {
      if (res.data.length > 0) {
        // 用户已存在，更新登录时间
        const db = wx.cloud.database()
        db.collection('users').doc(res.data[0]._id).update({
          data: {
            lastLoginTime: db.serverDate()
          }
        })
        resolve(res.data[0])
      } else {
        // 用户不存在，需要验证
        reject(new Error('用户未认证'))
      }
    }).catch(err => {
      console.error('检查认证失败:', err)
      reject(err)
    })
  })
}

// 获取当前用户信息
const getCurrentUser = () => {
  // 首先尝试从本地存储获取
  try {
    const cachedUser = wx.getStorageSync('cached_user')
    if (cachedUser) {
      // 同步到全局数据
      const app = getAppInstance()
      if (app && app.globalData) {
        app.globalData.currentUser = cachedUser
      }
      return cachedUser
    }
  } catch (e) {
    console.error('获取本地用户信息失败:', e)
  }
  
  // 如果本地存储没有，尝试从全局数据获取
  const app = getAppInstance()
  if (app && app.globalData && app.globalData.currentUser) {
    return app.globalData.currentUser
  }
  
  return null
}

// 设置当前用户信息
const setCurrentUser = (user) => {
  // 保存到全局数据
  const app = getAppInstance()
  if (app && app.globalData) {
    app.globalData.currentUser = user
  }
  
  // 同时保存到本地存储
  try {
    wx.setStorageSync('cached_user', user)
  } catch (e) {
    console.error('保存用户信息到本地失败:', e)
  }
}

// 清除当前用户信息
const clearCurrentUser = () => {
  // 清除全局数据
  const app = getAppInstance()
  if (app && app.globalData) {
    app.globalData.currentUser = null
  }
  
  // 清除本地存储
  try {
    wx.removeStorageSync('cached_user')
  } catch (e) {
    console.error('清除本地用户信息失败:', e)
  }
}

// 检查是否为管理员
const isAdmin = () => {
  const user = getCurrentUser()
  return user && user.role === 'admin'
}

// 页面权限守卫
const requireAuth = (page) => {
  const originalOnLoad = page.onLoad || function() {}
  
  page.onLoad = function(options) {
    checkAuthentication()
      .then(user => {
        setCurrentUser(user)
        originalOnLoad.call(this, options)
      })
      .catch(() => {
        wx.showModal({
          title: '需要身份验证',
          content: '请先进行身份验证',
          showCancel: false,
          success: () => {
            wx.reLaunch({
              url: '/pages/home/home'
            })
          }
        })
      })
  }
  
  return page
}

// 显示认证弹窗
const showAuthModal = (userInfo) => {
  return new Promise((resolve, reject) => {
    authenticateUser(userInfo)
      .then(user => {
        setCurrentUser(user)
        resolve(user)
      })
      .catch(err => {
        reject(err)
      })
  })
}

module.exports = {
  authenticateUser,
  checkAuthentication,
  getCurrentUser,
  setCurrentUser,
  clearCurrentUser,
  isAdmin,
  requireAuth,
  showAuthModal
}